package com.woan.api.servlet;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Enumeration;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.oreilly.servlet.MultipartRequest;
import com.woan.api.model.SysMessage;
import com.woan.api.services.MessageServerServices;
import com.woan.api.servlet.Addvoice.FileUtil;
import com.woan.api.util.CommonUtil;
import com.woan.api.util.CopyFile;
import com.woan.api.util.FuncDate;
import com.woan.api.util.Randoms;

public class yixuntest extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public yixuntest() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the GET method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		String oldPath =request.getServletContext().getRealPath("upload");
		MultipartRequest multi = null;
		int maxPostSize = 5000 * 1024 * 1024;
		multi = new MultipartRequest(request, oldPath, maxPostSize,"UTF-8");
		Enumeration filesname = multi.getFileNames();//文件
		FuncDate fd = new FuncDate();	
		PrintWriter out = response.getWriter();
		
		try 
		{
			System.out.println("--------------文件上传开始----------------");
			String filename = "";//文件名
			String name1 = (String) filesname.nextElement();
			filename = multi.getFilesystemName(name1);//获取上传文件的名称
			String newFileName = CommonUtil.RandomStrNumDate(4)+filename.substring(filename.lastIndexOf("."));//新的文件名
			System.out.println("newFileName="+newFileName);
			String newPath = oldPath+"/"+fd.FindCurSysTime();//文件保存目录
			File oldFile = new File(oldPath);
			if(!oldFile.exists()){//判断文件夹是否存在，不存在创建
				oldFile.mkdir();
			}
			File newFile = new File(newPath);
			if(!newFile.exists()){//判断文件夹是否存在，不存在创建
				newFile.mkdir();
			}
			File file2 = new File(newPath);
			if(!file2.exists()){//判断文件夹是否存在，不存在创建
				file2.mkdir();
			}
			CopyFile.CopyFile(oldPath+"/"+filename, newPath, newFileName);//复制文件
			CopyFile.doFolder(oldPath+"/"+filename);//删除原来文件
			System.out.println("--------------本地文件生成完成----------------");
			System.out.println("--------------视频服务器转码开始----------------");
			StringBuffer sResult = new StringBuffer();
			HttpURLConnection connection = null;
			String url = "http://115.28.33.49:3999/action/upload_file_task?random_seed=x1b2c25mmp&hash_key=a196bcb3e90f8199a364fa58e40a2052&output_tag=yixun_mp4&output_file_name="+newFileName;
			URL url1 = new URL(url);
			connection=(HttpURLConnection)url1.openConnection();
			//设置请求方式 
			connection.setRequestMethod("POST"); 
			connection.setDoOutput(true);
			byte[] f=new FileUtil().getFileByte(newPath+"/"+newFileName);
			//System.out.println("字节数组的大小:"+f.length); 
			// 分隔符 
			String BOUNDARY = "---------------------------7d4a6d158c9"; 
			StringBuffer sb = new StringBuffer(); 

			//发送文件: 
			sb = sb.append("--"); 
			sb = sb.append(BOUNDARY); 
			sb = sb.append("\r\n"); 
			sb = sb.append("Content-Disposition: form-data; name=\"s\"; filename=\""+newFileName+"\"\r\n"); 
			sb = sb.append("Content-Type: application/octet-stream\r\n\r\n"); 
			byte[] data = sb.toString().getBytes(); 
			byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes(); 
			//		         设置HTTP头: 
			connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+ BOUNDARY); 
			connection.setRequestProperty("Content-Length", String.valueOf(data.length + f.length + end_data.length)); 
			//		         输出: 
			OutputStream out1=connection.getOutputStream(); 
			out1.write(data); 
			out1.write(f); 
			out1.write(end_data); 
			out1.flush(); 
			//		         读取服务器响应： 
			BufferedReader in=new BufferedReader(new InputStreamReader(connection.getInputStream())); 
			String line=null; 
			while((line=in.readLine())!=null){ 
				if (sResult.length() > 0) {
					sResult.append("\n");
				}
				sResult.append(line);
			} 
			in.close(); 
			out1.close(); 
			System.out.println("--------------服务器转码完成----------------sResult="+sResult);
			System.out.println("--------------服务器转码完成----------------");
			String returnstr = sResult.toString().replaceAll(" ", "");
			String streamid = returnstr.substring(returnstr.lastIndexOf(":")+2,returnstr.length()-2);
			String urlplay = "http://115.28.33.49:3999/mobile/"+newFileName+".mp4";
			String backstr="<a href='"+urlplay+"'>播放</a>";
//			JSONObject json=new JSONObject();
//			json.accumulate("results", 0);
//			json.accumulate("errMsg", "发送成功");
//			json = messageServerServices.sendMessage(groupname,username,userpwd,sysmessage);
			response.setContentType("text/html");
			response.setHeader("Cache-control", "no-store");// HTTP 1.0
			response.setHeader("Pragma", "no-cache");
			response.setDateHeader("Expires", 0);
			response.setCharacterEncoding("utf-8");// 设置编码
			out = response.getWriter();
			out.println(backstr);
			out.flush();
			out.close();
				
		} catch (Exception e) {
			System.out.println("e = "+e);
		} 
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}
	class FileUtil { 

		 public byte[] getFileByte(String fileName) throws FileNotFoundException { 
		  FileInputStream fileInputStream = new FileInputStream(fileName); 
		  return getFileByte(fileInputStream); 
		 }
		 public byte[] getFileByte(URL url) throws IOException { 
			 if (url != null) { 
				 return getFileByte(url.openStream()); 
			 } else { 
				 return null; 
			 } 
		 }
		 public byte[] getFileByte(InputStream in) { 
			  ByteArrayOutputStream out = new ByteArrayOutputStream(4096); 
			  try 
			  { 
				  copy(in, out); 
			  } catch (IOException e) 
			  { 
				  e.printStackTrace(); 
			  } 
			  return out.toByteArray(); 

		 } 
		 private void copy(InputStream in, OutputStream out) throws IOException { 

			 try 
			 { 
				 byte[] buffer = new byte[4096]; 
				 int nrOfBytes = -1; 
				 while ((nrOfBytes = in.read(buffer)) != -1) 
				 { 
					 out.write(buffer, 0, nrOfBytes); 
				 } 
				 out.flush(); 
			 } catch (IOException e) 
			 { 

			 }
			 finally { 
				 try 
				 { 
					 if (in != null) 
					 { 
						 in.close(); 
					 } 
				 } catch (IOException ex) { 
				 } 
				 try { 
					 if (out != null) { 
						 out.close(); 
					 } 
				 } catch (IOException ex) { 
				 } 
			 } 
		 }
	}
}
